package com.up.vms.application.base.utils;
import java.io.File;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/**
 * 文件对象
 * 功能说明：<br>
 * 模块名称：<br>
 * 功能描述：<br>
 * 文件名称: <br>
 * 系统名称：<br>
 * 软件著作权：icelove 版权所有<br>
 * 开发人员：icelove <br>
 * 开发时间：2019/3/8 11:56<br>
 * 系统版本：1.0.0<br>
 */
public class RsaUtils {
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /**
     * 使用getPublicKey得到公钥,返回类型为PublicKey
     *
     * @param pubKey String to PublicKey
     * @throws Exception
     */
    public static PublicKey getPublicKey(String pubKey) throws Exception {
        byte[] keyBytes = CryptUtils.base64Decode2Byte(pubKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     * 转换私钥
     *
     * @param priKey String to PrivateKey
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String priKey) throws Exception {
        byte[] keyBytes = CryptUtils.base64Decode2Byte(priKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    //***************************签名和验证*******************************
    public static byte[] sign(byte[] data, String priKey) throws Exception {
        PrivateKey priK = getPrivateKey(priKey);
        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initSign(priK);
        sig.update(data);
        return sig.sign();
    }

    public static boolean verify(byte[] data, byte[] sign, String pubKey) throws Exception {
        PublicKey pubK = getPublicKey(pubKey);
        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initVerify(pubK);
        sig.update(data);
        return sig.verify(sign);
    }

    //************************加密**************************
    public static byte[] encrypt(byte[] text, String pubKey) throws Exception {
        PublicKey publicKey = getPublicKey(pubKey);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(text);
    }

    //************************解密**************************
    public static byte[] decrypt(byte[] text, String priKey) throws Exception {
        PrivateKey privateKey = getPrivateKey(priKey);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(text);
    }

    public static String parsePEM(String data) {
        if (data == null) return "";
        if (data.contains("--")) {
            data = data.replaceAll("\r", "");
            String[] items = data.split("\n");
            StringBuilder sb = new StringBuilder();
            for (String item : items) {
                if (item.contains("--")) {
                    continue;
                }
                sb.append(item).append("\r\n");
            }
            return sb.toString();
            //data = data.replaceAll("\\-\\-[\\W\\w]+?\\-\\-", "");
        }
        return data;
    }

//    //********************main函数：加密解密和签名验证*********************
//    public static void main(String[] args) throws Exception {
//        String text = "这是一段用来测试密钥转换的明文";
//        String str = "sdfas";
//        File penFile = new File("D:/cert/apiclient_key.pem");
//        String data = IoUtils.readFile(penFile);
//        System.out.println(data);
//        System.out.println(parsePEM(data));
//        //        String priKeyStr = IoUtils.fileToString("D:/cert/key.pem", "utf-8", true);
//        //        PrivateKey pk = getPrivateKey(priKeyStr);
//        //PublicKey pubKey = getPublicKey(pubKeyStr);
//        //        System.err.println("明文："+text);
//        //        byte[] bt_cipher = encrypt(str.getBytes(),"");
//        //        System.out.println("加密后："+ Base64.encodeBase64String(bt_cipher));
//        //
//        //        byte[] bt_original = decrypt(str.getBytes(),"");
//        //        String str_original = new String(bt_original);
//        //        System.out.println("解密结果:"+str_original);
//        //
//        //        str="被签名的内容";
//        //        System.err.println("\n原文:"+str);
//        //        byte[] signature=sign(str.getBytes(),"");
//        //        System.out.println("产生签名："+Base64.encodeBase64String(signature));
//        //        boolean status=verify(str.getBytes(), signature,"");
//        //        System.out.println("验证情况："+status);
//    }
}
